package com.starbucks.opencase.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.starbucks.opencase.data.daSession;
import com.starbucks.opencase.enums.enumCMKey;
import com.starbucks.opencase.enums.enumCMMark;
import com.starbucks.opencase.enums.enumCMTip;
import com.starbucks.opencase.function.funSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.time.LocalDateTime;

@Component
public class wsHandler implements WebSocketHandler {
    @Autowired
    private wsMessage message;
    @Autowired
    private funSession funSession;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        daSession.clients.add(session);
        System.out.println("["+ String.format("%29s",LocalDateTime.now().toString()).replaceAll(" ","0") +"]["+session.getId()+"][client]\t"+"已连接。");
        String q=session.getUri().getQuery();
        if(q==null)return;
        q=q.replaceAll("\\?","");
//        System.out.println(q);
        if(!q.isEmpty()){//重连
//            System.out.println(session.getUri().getQuery());
            ObjectNode on=new ObjectMapper().createObjectNode();
            on.put(enumCMKey.mark.name(), enumCMMark.login.ordinal());
            on.put(enumCMKey.command.name(), session.getUri().getQuery());
            message.handle(session.getId(), on);
        }
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        try{
            this.message.handle(session.getId(),new ObjectMapper().readTree(message.getPayload().toString()));
        }catch (Exception e){
            ObjectNode on=new ObjectMapper().createObjectNode();
            on.put(enumCMKey.mark.name(), enumCMMark.error.ordinal());
            on.put(enumCMKey.status.name(), false);
            on.put(enumCMKey.tip.name(), enumCMTip.error_handle.getTip());
            funSession.sendMessage(session.getId(), on);
            e.printStackTrace();
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("["+ String.format("%29s",LocalDateTime.now().toString()).replaceAll(" ","0") +"]["+session.getId()+"][client]\t"+"错误。\t"+exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        funSession.close(session.getId());
        System.out.println("["+ String.format("%29s",LocalDateTime.now().toString()).replaceAll(" ","0") +"]["+session.getId()+"][client]\t"+"已断开。\t"+closeStatus.toString());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
